<template>
  <div class="app-container">
    <div class="app-table">
      <div class="addButton"><el-button type="primary" @click="openAddUpdDialog(null)">新增用户</el-button></div>
      <el-table class="my-custom-table" v-loading="listLoading" :data="list" element-loading-text="Loading" he border
        fit highlight-current-row>
        <el-table-column align="center" label="序号" width="100%">
          <template slot-scope="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column label="用户名称" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.realName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="用户账号" align="center">
          <template slot-scope="scope">
            {{ scope.row.account }}
          </template>
        </el-table-column>
        <el-table-column label="角色" align="center">
          <template slot-scope="scope">
            <el-tag size="small" v-for="(role, index) in scope.row.roles" :key="index">{{ role }}</el-tag>
            <!-- <el-tag size="small" v-for="role in scope.row.roles" :key="role">{{ role }}</el-tag> -->
          </template>
        </el-table-column>
        <el-table-column label="联系电话" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.phoneText }}</span>
          </template>
        </el-table-column>

        <el-table-column label="创建时间" align="center">
          <template slot-scope="scope">
            {{ scope.row.createTime }}
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="120">
          <template slot-scope="scope">
            <el-button @click="openAddUpdDialog(scope.row)" type="text" size="small">
              编辑
            </el-button>
            <el-button @click="openDelDialog(scope.row.id)" type="text" size="small">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total > 0" :total="total" :page.sync="listQuery.pageIndex" :limit.sync="listQuery.pageSize"
        @pagination="getList" />
    </div>
    <el-dialog title="提示" :visible.sync="dialogVisible" width="30%" :before-close="handleClose">
      <span>这是一段信息</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="deleteRow()">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog :title="title" :visible.sync="addOrUpdateDialog" center v-if="addOrUpdateDialog">
      <el-form :model="userObject" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="编号" v-show="false">
          <el-input v-model="userObject.id"></el-input>
        </el-form-item>
        <el-form-item label="用户名称" prop="realName">
          <el-input v-model="userObject.realName"></el-input>
        </el-form-item>
        <el-form-item label="用户账号" prop="account">
          <el-input v-model="userObject.account"></el-input>
        </el-form-item>
        <el-form-item label="系统授权" prop="systems">
          <el-checkbox-group v-model="userObject.systems">
            <el-checkbox v-for="(systeam, index) in systeams" :label="systeam.key" :key="systeam.key">
              {{ systeam.value }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="角色授权" prop="roles" v-show="userObject.systems && userObject.systems.length > 0">
          <el-checkbox-group v-model="userObject.roles">
            <el-checkbox-button v-for="(role, index) in roles" :label="role.value" :key="role.value">{{ role.value
              }}</el-checkbox-button>
          </el-checkbox-group>
        </el-form-item>


        <el-form-item label="联系电话" prop="phoneText">
          <el-input v-model="userObject.phoneText"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="canAddUpdDialog()">取 消</el-button>
        <el-button type="primary" @click="submitUserInfo('ruleForm')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { queryUserPages, queryUserById, changeUserPwd, deleteUser, updateUser, createUser } from '@/api/user'
import { queryRoleDropDown } from '@/api/role'
import Pagination from '@/components/Pagination'
import { title } from '@/settings';
import { Message } from 'element-ui'
export default {
  name: 'Dashboard',
  components: { Pagination },
  data() {
    return {
      systeams: [
        {
          key: "4326811932741861377",
          value: "测试系统"
        }
      ],
      list: null,
      listLoading: true,
      listQuery: {
        pageIndex: 1,
        pageSize: 10
      },
      total: 0,
      dialogVisible: false,
      addOrUpdateDialog: false,
      deleteId: null,
      userObject: {
        systems: []
      },
      rules: {
        realName: [
          { required: true, message: '请输入用户名称', trigger: 'blur' },
        ],
        account: [
          { required: true, message: '请输入用户账号', trigger: 'change' }
        ],
        systems: [
          { type: 'array', required: true, message: '系统授权不能为空', trigger: 'change' }
        ],
        phoneText: [
          { required: true, message: '请输入联系电话', trigger: 'change' }
        ],
        roles: [
          { type: 'array', required: true, message: '角色授权不能为空', trigger: 'change' }
        ]
      },
      title: "",
      dropDown: null,
      roles: []
    }
  },
  mounted() {
  },
  async created() {
    await this.getDropDown()
    this.getList()
  },
  watch: {
    'userObject.systems': {
      handler(newVal, oldVal) {
        // 检查 newVal 是否为数组并且不为空
        if (newVal.length <= 0) {
          this.userObject.roles = []
        }

        if (Array.isArray(newVal) && newVal.length > 0) {
          console.log('Value changed:', newVal, oldVal);
          let thisRoles = [];
          newVal.forEach(item => {
            // 确保 dropDown 中有此项
            if (this.dropDown[item]) {
              thisRoles = thisRoles.concat(this.dropDown[item]);
            }
          });
          this.roles = thisRoles;
        }
      },
      deep: true, // 深度监听
      immediate: true // 初始化时立即执行一次
    }
  },
  methods: {
    async getDropDown() {
      this.listLoading = true
      const { data } = await queryRoleDropDown()
      this.dropDown = data
      this.listLoading = false
    },
    canAddUpdDialog() {
      this.addOrUpdateDialog = false

    },
    openDelDialog(id) {
      this.deleteId = id;
      this.dialogVisible = true;
    },
    openAddUpdDialog(row) {
      if (row) {
        this.title = "修改用户信息"
        //深拷贝一下
        this.userObject = JSON.parse(JSON.stringify(row))
      } else {
        this.userObject = {
          systems: [],
          roles: []
        }
        this.title = "新增用户信息"
      }
      this.addOrUpdateDialog = true
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done();
        })
        .catch(_ => { });
    },
    async getList() {
      this.listLoading = true
      const { data } = await queryUserPages(this.listQuery)
      this.list = data.data
      this.total = data.totalCount
      this.listLoading = false
    },
    async deleteRow() {
      this.listLoading = true
      console.log(3333333,this.deleteId)
      await deleteUser({ UserId: this.deleteId }).then(res => {
        this.listLoading = false
        this.dialogVisible = !res;
        if (res) {
          Message({
            message: "删除成功",
            type: 'success',
            duration: 5 * 1000
          })
          this.getList();
        }
      }).catch(err => {
        this.listLoading = false
        this.dialogVisible = false;
      })

    },
    async submitUserInfo(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          if (this.userObject.id) {
            await updateUser(this.userObject).then(res => {
              this.listLoading = false
              this.addOrUpdateDialog = !res;
              if (res) {
                Message({
                  message: "修改成功",
                  type: 'info',
                  duration: 5 * 1000
                })
                this.getList();
              }
            }).catch(err => {
              this.listLoading = false
              this.addOrUpdateDialog = false;
            })
          } else {
            await createUser(this.userObject).then(res => {
              this.listLoading = false
              this.addOrUpdateDialog = !res;
              if (res) {
                Message({
                  message: "新增成功",
                  type: 'success',
                  duration: 5 * 1000
                })
                this.getList();
              }
            }).catch(err => {
              this.listLoading = false
              this.addOrUpdateDialog = false;
            })
          }
        }
      });
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  .app-table {
    margin: 25px 100px 75px 100px
  }

  .addButton {
    margin: 0px 0px 20px 94%
  }

  .text {
    font-size: 14px;
  }

  .item {
    margin-bottom: 18px;
  }

  .clearfix:before,
  .clearfix:after {
    display: table;
    content: "";
  }

  .clearfix:after {
    clear: both
  }

  .box-card {
    width: 480px;
  }

}

/* 只修改特定表格的表头颜色 */
.my-custom-table .el-table th {
  background-color: #F56C6C;
  /* 你想要的颜色 */
}
</style>
